package tr.edu.yildiz.ce.dap.appagent.command.deployment.base;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.DeploymentProcess;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;

public abstract class AbstractCommand {
	
	AbstractProcess process;
	
	public AbstractCommand(AbstractProcess process) {
		this.process = process;
	}
	
	public abstract DapMessage execute(DapMessage msg) throws BasicAgentException;
	
	public abstract DapMessage rollback(DapMessage msg) throws BasicAgentException;
	
	protected void install(String bundlePath){
		synchronized (getContext()) {
			try {
				getContext().installBundle(bundlePath);
			} catch (BundleException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void unInstall(String name,String version){
		synchronized (getContext()) {
			try {
				Bundle[] bundles = getContext().getBundles();
				for (Bundle b : bundles) {
					if (b.getSymbolicName().equals(name) 
							&& b.getVersion().equals(version)){
						b.uninstall();
						return;
					}
				}
			} catch (BundleException e) {
				e.printStackTrace();
			}
		}
	}
	
	private BundleContext getContext(){
		return process.getProcessManager().getContext();
	}
	
	public AbstractProcess getProcess() {
		return process;
	}
	
}
